/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Control;

import java.io.*;
import javax.swing.*;
import jxl.write.*;
import jxl.*;

/**
 *
 * @author LIZ
 */
public class ExcelTableExporter {
    /*public ExcelTableExporter() { }
    public void exportTable(JTable table, File file) throws IOException {
    TableModel model = table.getModel();
    FileWriter out = new FileWriter(file);
    for(int i=0; i < model.getColumnCount(); i++) {
    out.write(model.getColumnName(i) + "\t");
    }
    out.write("\n");

    for(int i=0; i< model.getRowCount(); i++) {
    for(int j=0; j < model.getColumnCount(); j++) {
    out.write(model.getValueAt(i,j).toString()+"\t");
    }
    out.write("\n");
    }

    out.close();
    System.out.println("write out to: " + file);
    }*/

    private File file;
    private JTable table;
    private String nombreTab;

    public ExcelTableExporter(JTable table, File file, String nombreTab) {
        this.file = file;
        this.table = table;
        this.nombreTab = nombreTab;

    }

    public boolean export() {
        try {

            DataOutputStream out = new DataOutputStream(new FileOutputStream(file));
            WritableWorkbook w = Workbook.createWorkbook(out);

            WritableSheet s = w.createSheet(nombreTab, 0);

            for (int i = 0; i < table.getRowCount(); i++) {
                for (int j = 0; j < table.getColumnCount(); j++) {
                    Object objeto = table.getValueAt(j, i);
                    s.addCell(new Label(j, i, String.valueOf(objeto)));
                }
            }
            w.write();

            w.close();
            out.close();

            return true;

        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (WriteException ex) {
            ex.printStackTrace();
        }

        return false;
    }
}
